package com.yh.zz_hlj.modules.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.networkbench.agent.impl.NBSAppAgent;
import com.yh.zz_hlj.AppConfig;
import com.yh.zz_hlj.AppContext;
import com.yh.zz_hlj.R;
import com.yh.zz_hlj.base.BaseActivity;
import com.yh.zz_hlj.common.UIHelper;
import com.yh.zz_hlj.common.UpdateManager;
import com.yh.zz_hlj.modules.bean.CKComp;
import com.yh.zz_hlj.modules.bean.SimpleBackPage;
import com.yh.zz_hlj.modules.bean.User;
import com.yh.zz_hlj.modules.widget.dragexpandgrid.CustomGroup;
import com.yh.zz_hlj.modules.widget.dragexpandgrid.other.DargChildInfo;
import com.yh.zz_hlj.modules.widget.dragexpandgrid.other.DragIconInfo;

import java.util.ArrayList;

import butterknife.InjectView;

import static com.yh.zz_hlj.AppConfig.SCN_CUST_ACTION_SCODE;

public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
    private final String TAG = MainActivity.class.getSimpleName();
    @InjectView(R.id.p3_group)
    CustomGroup p3_group;
    @InjectView(R.id.profile_image)
    ImageView profile_image;
    @InjectView(R.id.tv_username)
    TextView tv_username;
    @InjectView(R.id.tv_userdepartment)
    TextView tv_userdepartment;
    @InjectView(R.id.tv_userduty)
    TextView tv_userduty;
    @InjectView(R.id.tv_user_pay)
    TextView tv_user_pay;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private Toolbar toolbar;
    private DrawerLayout drawer;
    private FloatingActionButton fab;
    private String userType;
    private ImageView bannner;
    private RelativeLayout headerBackground;
    private ArrayList<CKComp> cmps;

    private long exitTime = 0; ////记录第一次点击的时间

    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                handleOtherText(message);
            }
        }
    };

    private boolean isLoaction = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected boolean hasBackButton() {
        return true;
    }

    @Override
    protected int getActionBarTitle() {
        return R.string.action_settings;
    }

    private ArrayList<DragIconInfo> initAllOriginalInfo() {
        ArrayList<DragIconInfo> iconInfoList = new ArrayList<DragIconInfo>();
        User user = AppContext.getInstance().getCurrentUser();
        if (user != null) {
            p3_group.setCOLUMNUM(2);
            iconInfoList.add(new DragIconInfo(1, "销售出库", R.drawable.scan3, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(2, "产品入库", R.drawable.find3, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(3, "其他出库", R.drawable.scan2, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(4, "外购入库", R.drawable.find1, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(5, "调拨单", R.drawable.scan1, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
            iconInfoList.add(new DragIconInfo(6, "装箱", R.drawable.find2, DragIconInfo.CATEGORY_ONLY, new ArrayList<DargChildInfo>(), 0));
        } else {
            Snackbar.make(p3_group, "请重新登录!", Snackbar.LENGTH_SHORT).show();
            this.finish();
        }
        return iconInfoList;
    }


    /**
     * 初始化基础View
     */
    public void initView() {
        User user = AppContext.getInstance().getCurrentUser();
        tv_user_pay.setOnClickListener(this);
        if (user != null) {
            tv_username.setText(user.getName());
//            tv_userdepartment.setText(user.getDepartmentName() + "-" + user.getDuty() + "-" + user.getGXName());
//            tv_userduty.setText(user.getGXName());
            tv_user_pay.setText("当月工资：" + user.getFMonthMoney() + "元");
        } else {
            Snackbar.make(tv_username, "获取用户失败，请重新登录", Snackbar.LENGTH_SHORT).show();
            Intent main = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(main);
            finish();
        }
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        bannner = (ImageView) findViewById(R.id.bannner);
        //标题
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        if (user != null) {
            collapsingToolbarLayout.setTitle(user.getName());
        }
        //fab
        fab = (FloatingActionButton) findViewById(R.id.fab);
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
        final int fabBottomMargin = lp.bottomMargin;
    }

    @Override
    public void initData() {
        NBSAppAgent.setLicenseKey("5a853218974d4b32b0cb77b6fb127256").start(this.getApplicationContext());
        checkUpdate();
        initView();
        initDrawer();
        p3_group.initData(initAllOriginalInfo());
        User mUser = AppContext.getInstance().getCurrentUser();
        if (mUser != null) {
            userType = mUser.getDuty();
        }
        // Register receiver
//        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
//        registerReceiver(mSamDataReceiver, intentFilter);
    }

    private void checkUpdate() {
//        if (!AppContext.get(AppConfig.KEY_CHECK_UPDATE, true)) {
//            return;
//        }
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                new UpdateManager(MainActivity.this, false).checkUpdate();
            }
        }, 2000);
    }

    /**
     * 初始化抽屉
     */
    private void initDrawer() {
        //https://segmentfault.com/a/1190000004151222
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
        headerBackground = (RelativeLayout) headerLayout.findViewById(R.id.header_background);
//        if (mSetting.getInt(Setting.HOUR, 0) < 6 || mSetting.getInt(Setting.HOUR, 0) > 18) {
//            //headerBackground.setBackground(this.getResources().getDrawable(R.mipmap.header_back_night)); 过时
//            headerBackground.setBackground(ContextCompat.getDrawable(this, R.mipmap.header_back_night));
//        }
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
                R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
    }

    /**
     * Called when an item in the navigation menu is selected.
     *
     * @param item The selected item
     * @return true to display the item as the selected item
     */
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_about:
                UIHelper.showAboutOSC(this);
                break;
            case R.id.sync_data:
//                showWaitDialog();
//                RetrofitSingleton.getApiService(MainActivity.this).
//                        SyncInfosAll()
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(observer);
                break;
            case R.id.change_pwd:
                UIHelper.showSimpleBack(this, SimpleBackPage.CHANGE_PWD, null, "修改密码");
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return false;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            //super.onBackPressed();
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Snackbar.make(fab, "再按一次退出程序", Snackbar.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_user_pay:
//                UIHelper.showUserPayDetail(this, "工资详情");
                break;
            default:
                break;
        }
    }

    private void handleOtherText(final String text) {
        // yhzw#gxhb#Work43
        String[] sp = text.split("#");
        if (sp != null) {
            if (sp.length >= 3) {
                if (sp[0].equals("yhzw")) {
                    switch (sp[1]) {
                        case "gxhb":
                            if ("车间工人".equals(userType)) {
                                UIHelper.showWorks(this, sp[2]);
                            } else {
                                Snackbar.make(p3_group, "员工类型非车间工人，不允许工序扫码操作", Snackbar.LENGTH_SHORT).show();
                            }
                            break;
                        case "ck":
                            if ("仓库管理".equals(userType)) {
                                if (sp.length == 6) {
                                    int mcount = Integer.parseInt(sp[3]);
                                    if (cmps.size() == 0) {
                                        CKComp cm = new CKComp();
                                        cm.setCount(Integer.parseInt(sp[3]));
                                        cm.setItemDN(sp[4]);
                                        cm.setType(sp[5]);
                                        if (mcount == 1) {
                                            cm.setAll(true);
                                        }
                                        cmps.add(cm);
//                                        UIHelper.showCKDan(this,cmps, cmps);
                                    } else {
                                        for (int m = 0; m < cmps.size(); m++) {
                                            CKComp outcp = cmps.get(m);
                                            String outype = outcp.getType();
                                            String outid = outcp.getItemDN();
                                            if (sp[5].equals(outype) && sp[4].equals(outid)) {
                                                Snackbar.make(p3_group, "已经扫描过了！", Snackbar.LENGTH_SHORT).show();
                                                m = cmps.size();
                                            } else if (sp[4].equals(outid) && !sp[5].equals(outype)) {
                                                outcp.setAll(true);
                                                Snackbar.make(p3_group, "主副门已经全部扫描过了！", Snackbar.LENGTH_SHORT).show();
                                            } else if (!sp[4].equals(outid)) {
                                                if (m == cmps.size() - 1) {
                                                    if (!sp[4].equals(outid)) {
                                                        CKComp cm = new CKComp();
                                                        cm.setCount(Integer.parseInt(sp[3]));
                                                        cm.setItemDN(sp[4]);
                                                        cm.setType(sp[5]);
                                                        if (mcount == 1) {
                                                            cm.setAll(true);
                                                        }
                                                        cmps.add(cm);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (cmps.size() > 0) {
//                                        iv_count.setVisibility(View.VISIBLE);
                                    }
//                                    updateUnreadLabel_tweet();
//                                    restartCamera();
                                }
                            } else {
                                Snackbar.make(p3_group, "错误的出入库二维码！", Snackbar.LENGTH_SHORT).show();
//                                restartCamera();
                            }
                            break;
                        default:
                            Snackbar.make(p3_group, "未定义的操作类型", Snackbar.LENGTH_SHORT).show();
//                            restartCamera();
                            break;
                    }
                } else {
                    Snackbar.make(p3_group, "错误的条码", Snackbar.LENGTH_SHORT).show();
//                    restartCamera();
                }
            } else {
                Snackbar.make(p3_group, "错误的条码", Snackbar.LENGTH_SHORT).show();
//                restartCamera();
            }
        } else {
            Snackbar.make(p3_group, "错误的条码", Snackbar.LENGTH_SHORT).show();
//            restartCamera();
        }
    }


}
